package com.lemon.exam.common.entity.dto;

import com.lemon.exam.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Locale;

/**
 * 验证码信息封装类
 *
 * @param uuid
 * @param code
 * @param image
 */
@Slf4j
public record CaptchaDTO(String uuid, String code, BufferedImage image) {
    /**
     * 获取Base64编码的图片（带前缀，可直接用于img标签）
     */
    public String getBase64Image(String type) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, type, baos);
            return "data:image/%s;base64,".formatted(type.toLowerCase(Locale.ENGLISH)) + Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new CustomException("生成验证码Base64失败");
        }
    }

    /**
     * 获取图片字节数组
     */
    public byte[] getImageBytes(String type) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, type, baos);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new CustomException("生成验证码字节数组失败");
        }
    }
}
